package com.phshopping.charge.api.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.dubbo.config.annotation.Reference;
import com.ph.shopping.common.core.exception.BizException;
import com.ph.shopping.common.util.transform.MoneyTransUtil;
import com.ph.shopping.facade.pay.enums.PayStatusEnum;
import com.ph.shopping.facade.pay.service.IPayService;
import com.ph.shopping.facade.pay.utils.PayecoUtils;
import com.ph.shopping.facade.pay.vo.PayecoOrderVo;

/**
 * @项目：phshopping-api-pay
 * @描述：易联支付回调
 * @作者： 张霞
 * @创建时间： 14:29 2017/3/23
 * @Copyright @2017 by zhangxia
 */
@Controller
@RequestMapping("api/pay")
public class PayecoCallBackController {
    // 创建公共日志
    protected Logger logger = LoggerFactory.getLogger(this.getClass());
    
    @Reference(version="1.0.0")
    private IPayService payService;
    
    /**
     * 易联支付异步回调方法
     * @param model
     * @param request
     * @param response
     * @throws IOException
     * @author Mr.Chang
     * @since 2017.03.29
     */
    @RequestMapping(value="/payecoReturnAsync",method= RequestMethod.POST)
    public void payecoAsyncCallback(Model model, HttpServletRequest request, HttpServletResponse response){
        logger.info("****************开始进入支付异步回调***********");
        
        try{
        	final String CharSet = "UTF-8";
        	response.setContentType("text/html");
        	request.setCharacterEncoding(CharSet);
        	response.setCharacterEncoding(CharSet);
        	PrintWriter out = response.getWriter();
        	String response_text = request.getParameter("response_text");
        	
	        if(response_text != null && !"".equals(response_text)){
	        	//解析xml报文数据获取支付结果状态
	            String decryptXml = PayecoUtils.decryptMiWen(response_text);
	            logger.info("异步返回报文："+decryptXml);
	            String respCode = StringUtils.substringBetween(decryptXml,"<RespCode>","<");
	            
	            //回调订单号
	            String orderNum=PayecoUtils.getValue(decryptXml,"MerchantOrderNo");
	            //回调返回的MD5报文加密码
	            String mac=PayecoUtils.getValue(decryptXml,"MAC");
	            //回调金额
	            String amount=PayecoUtils.getValue(decryptXml,"Amount");
	            
	            logger.info("回调参数===>金额:"+amount+"  MAC值："+mac);
	            
	            logger.info("金额转换："+MoneyTransUtil.transMultiDouble(Double.valueOf(amount)));
	            //截取操作的业务代码
	            String bizCode=PayecoUtils.getOrderBizCode(orderNum);
	            logger.info("充值订单号："+orderNum+"异步回调返回结果："+respCode);
	            
	            //根据订单号查询订单信息
	            PayecoOrderVo pv=payService.getOrderInfoByNum(orderNum, bizCode);
	            if(org.springframework.util.StringUtils.isEmpty(pv)){
	            	logger.error("支付异常,订单号不存在!");
	            }
	            
	            if (respCode.equals("0000")) {
	            	//判断MD5校验是否正确
	            /*	if(org.springframework.util.StringUtils.isEmpty(pv.getMD5())||!pv.getMD5().equals(mac)){
	            		//支付失败业务操作
	              		payService.checkAndUpdateOrderStatus(bizCode, orderNum, PayStatusEnum.PAY_FAILURE.getCode());
	            		logger.error("支付返回的MD5报文码于发送前不匹配");
	            	}*/
	             	//判断回调金额是否正确
	          		if(org.springframework.util.StringUtils.isEmpty(amount)||pv.getScore()!=MoneyTransUtil.transMultiDouble(Double.valueOf(amount))){
	          			//支付失败业务操作
	              		payService.checkAndUpdateOrderStatus(bizCode, orderNum, PayStatusEnum.PAY_FAILURE.getCode(),respCode);
	          			logger.error("订单："+orderNum+"支付异常,回调金额错误");
	          		}
	          		//支付成功业务操作
	          		payService.checkAndUpdateOrderStatus(bizCode, orderNum, PayStatusEnum.PAY_SUCCESS.getCode(),respCode);
	          		logger.error("订单："+orderNum+"交易成功");
				}else{
					//支付异常处理
					payService.checkAndUpdateOrderStatus(bizCode,orderNum, PayStatusEnum.PAY_FAILURE.getCode(),respCode);
	                logger.error("订单号："+orderNum+"支付失败,错误代码："+respCode);
					
				}
	            //通知易联接收成功
	            out.print("0000");
	            out.flush();
	            out.close();
	            logger.info("decrypt后的内容:"+decryptXml);
	            logger.info("****************完成支付异步回调***********");
	        }
        }catch(BizException e){
        	logger.error("回调更新业务数据异常："+e);
        }catch (IOException e) {
        	logger.error("支付回调异常："+e);
		}
       
    }
    
    /**
     * 易联同步回调
     * @param request
     * @param response
     * @return
     * @throws Exception
     * @author Mr.Chang
     * @throws UnsupportedEncodingException 
     * @since 2017.03.29
     */
    @RequestMapping(value="/payecoReturnSync",method=RequestMethod.GET)
    public String payecoSyncCallback(Model model,HttpServletRequest request,HttpServletResponse response) {
    		logger.info("****************进入支付同步回调***********");
    		String mv=null;
    		try {
		        final String CharSet = "UTF-8";
		        response.setContentType("text/html");
		        request.setCharacterEncoding(CharSet);
		        response.setCharacterEncoding(CharSet);
		        String response_text = request.getParameter("response_text");
		        //解析返回报文
		        if(response_text != null && !"".equals(response_text)){
		        	String decryptXml;
						decryptXml = PayecoUtils.decryptMiWen(response_text);
					//解析xml文件查看支付状态
		        	logger.info("同步返回报文："+decryptXml);
		        	String respCode = StringUtils.substringBetween(decryptXml,"<RespCode>","<");
		        	//回调订单号
		            String orderNum=PayecoUtils.getValue(decryptXml,"MerchantOrderNo");
		            //回调返回的MD5报文加密码
		            String mac=PayecoUtils.getValue(decryptXml,"MAC");
		            //回调金额
		            String amount=PayecoUtils.getValue(decryptXml,"Amount");
		            
		            logger.info("同步回调参数===>金额:"+amount+"  MAC值："+mac);
		            logger.info("金额转换："+MoneyTransUtil.transMultiDouble(Double.valueOf(amount)));
		        	logger.info("订单号："+orderNum+"异步回调返回结果："+respCode);
		        	
		        	//判断是否支付回调成功
		            if (respCode.equals("0000")) {
		          		logger.error("订单："+orderNum+"同步回调成功");
		          		model.addAttribute("msg", "订单支付成功");
		          		mv="pay/payeco/success";
					}else{
						//支付异常处理
		                logger.error("订单号："+orderNum+"支付失败,错误代码："+respCode);
		                model.addAttribute("msg", "支付失败,错误代码："+respCode);
		          		mv="pay/payeco/failure";
					}
		        }else{
		        	logger.error("未返回订单支付信息");
		        	model.addAttribute("msg", "未返回订单支付信息");
		        	mv="error/unAuthorization";
		        }
	    	} catch (Exception e) {
				logger.error("解析报文异常："+e);
				model.addAttribute("msg", "支付异常报文解析异常");
	        	mv="error/error";
			}
	        logger.info("****************完成支付同步回调***********");
        return mv;
    }

}
